import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:stacked/stacked.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/app/router/app_router.dart';
import 'package:vista/features/profile/viewmodels/settings_viewmodel.dart';
import 'package:vista/shared/constants/color.dart';
import 'package:vista/shared/utils/flash_notifier.dart';
import 'package:vista/shared/utils/url_open.dart';
import 'package:vista/shared/utils/widget_extension.dart';

/// 设置页面视图
/// 系统设置功能页面
class SettingsView extends StatelessWidget {
  const SettingsView({super.key});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<SettingsViewModel>.reactive(
      viewModelBuilder: () => SettingsViewModel(getIt.get()),
      builder: (context, viewModel, child) {
        return Scaffold(
          body: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my-background.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child: [
                // 顶部标题栏
                _buildHeader(context),
                // 可滚动内容
                Expanded(
                  child: SingleChildScrollView(
                    child: [
                          SizedBox(height: 20.h),
                          // 系统设置卡片
                          _buildSystemSettingsCard(context, viewModel),
                          SizedBox(height: 100.h), // 底部留白
                        ]
                        .verticalShot(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                        )
                        .frameHorizontal(14.w),
                  ),
                ),
                // 底部退出登录按钮
                _buildLogoutButton(context, viewModel),
              ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
            ),
          ),
        );
      },
    );
  }

  /// 构建顶部标题栏
  Widget _buildHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 16.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Image.asset(
              'assets/images/back.png',
              width: 24.w,
              height: 24.w,
            ),
          ),
          Expanded(
            child: Center(
              child: Text(
                'Set Up',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w800,
                  fontFamily:
                      GoogleFonts.alegreyaSans(
                        fontWeight: FontWeight.w800,
                      ).fontFamily,
                  color: Colors.black,
                ),
              ),
            ),
          ),
          SizedBox(width: 24.w), // 平衡返回按钮
        ],
      ),
    );
  }

  /// 构建系统设置卡片
  Widget _buildSystemSettingsCard(
    BuildContext context,
    SettingsViewModel viewModel,
  ) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(color: Colors.black.withOpacity(0.1), width: 1.w),
      ),
      padding: EdgeInsets.all(14.w),
      child: [
        // 标题
        Text(
          'System Settings',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w800,
            fontFamily:
                GoogleFonts.alegreyaSans(
                  fontWeight: FontWeight.w800,
                ).fontFamily,
            color: Colors.black,
          ),
        ),
        SizedBox(height: 16.h),
        // 设置项列表
        _buildSettingItem(
          context,
          'Privacy Policy',
          onTap: () => UrlOpen.openPrivacyUrl(),
        ),
        SizedBox(height: 12.h),
        _buildSettingItem(
          context,
          'Terms Of Service',
          onTap: () => UrlOpen.openServiceUrl(),
        ),
        SizedBox(height: 12.h),
        _buildSettingItem(
          context,
          'Delete Account',
          onTap: () => _showDeleteAccountDialog(context, viewModel),
        ),
      ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  /// 构建设置项
  Widget _buildSettingItem(
    BuildContext context,
    String title, {
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Row(
        children: [
          Expanded(
            child: Text(
              title,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w400,
                fontFamily:
                    GoogleFonts.alegreyaSans(
                      fontWeight: FontWeight.w400,
                    ).fontFamily,
                color: Colors.black87,
              ),
            ),
          ),
          Icon(Icons.chevron_right, size: 20.w, color: Colors.black54),
        ],
      ),
    );
  }

  /// 构建退出登录按钮
  Widget _buildLogoutButton(BuildContext context, SettingsViewModel viewModel) {
    return Container(
      padding: EdgeInsets.fromLTRB(14.w, 0, 14.w, 20.h),
      child: ElevatedButton(
        onPressed:
            viewModel.isBusy
                ? null
                : () async {
                  await viewModel.logout();
                  if (context.mounted) {
                    FlashNotifier.flashSuccess('Logout successful');
                    Navigator.of(
                      context,
                    ).pushNamedAndRemoveUntil(Routes.main, (route) => false);
                  }
                },
        style: ElevatedButton.styleFrom(
          padding: EdgeInsets.symmetric(vertical: 16.h),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12.r),
          ),
          backgroundColor: ColorConstants.accentColor,
          foregroundColor: Colors.white,
          elevation: 0,
        ),
        child: Text(
          'Log Out',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
            fontFamily:
                GoogleFonts.alegreyaSans(
                  fontWeight: FontWeight.w600,
                ).fontFamily,
          ),
        ),
      ),
    );
  }

  /// 显示删除账号确认弹窗
  Future<void> _showDeleteAccountDialog(
    BuildContext context,
    SettingsViewModel viewModel,
  ) async {
    final result = await showDialog<bool>(
      context: context,
      builder:
          (context) => Dialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20.r),
            ),
            insetPadding: EdgeInsets.symmetric(
              horizontal: 40.w,
              vertical: 80.h,
            ),
            elevation: 0,
            backgroundColor: Colors.transparent,
            child: Container(
              constraints: BoxConstraints(maxWidth: 320.w, minWidth: 280.w),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(20.r),
                gradient: const LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [Color(0xFFFFA680), Color(0xFFFFEBE6)],
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 20.w,
                    offset: Offset(0, 10.h),
                  ),
                ],
              ),
              child: [
                    // 标题
                    Text(
                      'Delete Account',
                      style: TextStyle(
                        fontSize: 22.sp,
                        fontWeight: FontWeight.w800,
                        fontFamily:
                            GoogleFonts.alegreyaSans(
                              fontWeight: FontWeight.w800,
                            ).fontFamily,
                        color: Colors.black87,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    SizedBox(height: 16.h),
                    // 描述
                    Text(
                      'Are you sure you want to delete your account?',
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: Colors.black.withOpacity(0.7),
                        height: 1.5,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    SizedBox(height: 36.h),
                    // 按钮组
                    [
                      // 取消按钮
                      Expanded(
                        child: OutlinedButton(
                          onPressed: () => Navigator.of(context).pop(false),
                          style: OutlinedButton.styleFrom(
                            padding: EdgeInsets.symmetric(vertical: 16.h),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12.r),
                            ),
                            side: BorderSide(
                              color: Colors.black.withOpacity(0.2),
                              width: 1.5,
                            ),
                          ),
                          child: Text(
                            'Cancel',
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w600,
                              color: Colors.black87,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(width: 14.w),
                      // 删除按钮
                      Expanded(
                        child: ElevatedButton(
                          onPressed: () => Navigator.of(context).pop(true),
                          style: ElevatedButton.styleFrom(
                            padding: EdgeInsets.symmetric(vertical: 16.h),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12.r),
                            ),
                            backgroundColor: Colors.red,
                            foregroundColor: Colors.white,
                            elevation: 0,
                          ),
                          child: Text(
                            'Delete',
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),
                    ].horizontalGallery(),
                  ]
                  .verticalShot(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                  )
                  .frameAll(32.w),
            ),
          ),
    );

    if (result == true && context.mounted) {
      await viewModel.deleteAccount();
      if (context.mounted) {
        FlashNotifier.flashSuccess('Account deleted successfully');
        Navigator.of(
          context,
        ).pushNamedAndRemoveUntil(Routes.main, (route) => false);
      }
    }
  }
}
